<template>
  <a-card title="">
    <a-form layout="inline">
      <a-form-item>
        <a-select v-model="listQuery.select_value" style="width: 120px">
          <a-select-option value="全部">全部</a-select-option>
          <a-select-option value="title">试卷标题</a-select-option>
          <a-select-option value="name">考试名称</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-input-search enterButton @search="onSearch" />
      </a-form-item>
    </a-form>
    <a-tabs :activeKey="activeKey" @tabClick="callback">
      <a-tab-pane tab="查考考试" key="1">
        <a-table :columns="columns" :dataSource="data" bordered rowKey="id" :pagination="false">
          <template slot="name" slot-scope="text">
            <a href="javascript:;">{{ text }}</a>
          </template>
          <template slot="hascompletion" slot-scope="text">
            <a-tag color="pink" v-if="text == 0">机器改卷</a-tag>
            <a-tag color="blue" v-else>需人工改卷</a-tag>
          </template>
          <template slot="action" slot-scope="text, record, index">
            <a-button type="primary" @click="editExam(record.id)" v-if="text == 1">查看/编辑</a-button>
            <a-button type="primary" disabled v-else>考试失效无法编辑</a-button>
          </template>
        </a-table>
        <a-pagination showSizeChanger :pageSize.sync="listQuery.page_size" :pageSizeOptions="pagesizeoptions"
          @showSizeChange="onShowSizeChange" :total="total" @change="onChange" v-model="listQuery.page_number" />
      </a-tab-pane>
      <a-tab-pane tab="修改/添加" key="2">
        <div id="components-form-demo-advanced-search">
          <a-form class="ant-advanced-search-form" :form="form">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="试卷标题">
                  <a-input :disabled="disabledform" placeholder="试卷标题" v-decorator="['title', { rules: [{ required: true, message: '不能为空' }] }]" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="开考日期">
                  <a-date-picker :disabled="disabledform" v-decorator="['stime', { rules: [{ required: true, message: '不能为空' }] }]"
                    showTime format="YYYY-MM-DD HH:mm:ss" placeholder="Select Time" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="结束日期">
                  <a-date-picker :disabled="disabledform" v-decorator="['etime', { rules: [{ required: true, message: '不能为空' }] }]"
                    showTime format="YYYY-MM-DD HH:mm:ss" placeholder="Select Time" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="考试时间(分)">
                  <a-input v-decorator="['time', { rules: [{ required: true, validator: this.rules.isnumber }] }]"
                    :disabled="disabledform" placeholder="考试时间(分)" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="考试名称">
                  <a-input :disabled="disabledform" v-decorator="['name', { rules: [{ required: true, message: '不能为空' }] }]"
                    placeholder="考试名称" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="应考人员说明">
                  <a-input :disabled="disabledform" v-decorator="['describe', { rules: [{ required: false, message: '可以为空' }] }]"
                    placeholder="应考人员说明" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="考试题型">
                  <a-checkbox-group :options="plainOptions" v-decorator="['typelist', { rules: [{ required: true, message: '考试题型必须选择,请选择!' }] }]" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="单选题数">
                  <a-input :disabled="disabledform" v-decorator="['dxsize', { rules: [{ required: true, validator: this.rules.isnumber }] }]"
                    placeholder="无请填写0" />
                </a-form-item>
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="单选题分数">
                  <a-input :disabled="disabledform" v-decorator="['dxcustomscore', { rules: [{ required: true, validator: this.rules.isnumber }] }]"
                    placeholder="默认2分" />
                </a-form-item>
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="多选题数">
                  <a-input :disabled="disabledform" v-decorator="['dxxsize', { rules: [{ required: true, validator: this.rules.isnumber }] }]"
                    placeholder="无请填写0" />
                </a-form-item>
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="多选题分数">
                  <a-input :disabled="disabledform" v-decorator="['dxxcustomscore', { rules: [{ required: true, validator: this.rules.isnumber }] }]"
                    placeholder="默认2分" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="判断题数">
                  <a-input :disabled="disabledform" v-decorator="['pdsize', { rules: [{ required: true, validator: this.rules.isnumber }] }]"
                    placeholder="无请填写0" />
                </a-form-item>
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="判断题分数">
                  <a-input :disabled="disabledform" v-decorator="['pdcustomscore', { rules: [{ required: true, validator: this.rules.isnumber }] }]"
                    placeholder="默认2分" />
                </a-form-item>
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="填空题数">
                  <a-input :disabled="disabledform" v-decorator="['tksize', { rules: [{ required: true, validator: this.rules.isnumber }] }]"
                    placeholder="无请填写0" />
                </a-form-item>
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="填空题分数">
                  <a-input :disabled="disabledform" v-decorator="['tkcustomscore', { rules: [{ required: true, validator: this.rules.isnumber }] }]"
                    placeholder="默认5分" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item has-feedback :label-col="labelCol" :wrapper-col="wrapperCol" label="考试状态">
                  <a-select v-decorator="['invalid', { rules: [{ required: true, message: '请选择!' }] }]" style="width: 120px">
                    <a-select-option value="1">开放</a-select-option>
                    <a-select-option value="0">关闭</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="限制次数">
                  <a-input :disabled="disabledform" v-decorator="['limit', { rules: [{ required: true, validator: this.rules.isnumber }] }]"
                    placeholder="限制次数" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="科目/方案">
                  <a-select v-decorator="['subjectid', { rules: [{ required: true, message: '请选择!' }] }]" style="width: 120px"
                    @change="handleProvinceChange">
                    <a-select-option v-for="(item, index) in subPro" :value="item.subject.id" :key="item.subject.id">{{ item.subject.name }}</a-select-option>
                  </a-select>
                  <a-select v-decorator="['projectid', { rules: [{ required: false, message: '请选择!' }] }]" style="width: 120px">
                    <a-select-option v-for="(pitem, pindex) in pRo" :key="pitem.id" :value="pitem.id">{{ pitem.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24" :style="{ textAlign: 'right' }">
                <a-button type="primary" html-type="submit" @click="handleSubmitAdd">添加</a-button>
                <a-button type="danger" :style="{ marginLeft: '8px' }" v-show="editExamData.exam" @click="handleSubmitSave">修改</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-tab-pane>
    </a-tabs>

    <a-modal title="查看/编辑" centered v-model="modal2Visible" @ok="() => (modal2Visible = false)">
      <a-card></a-card>
    </a-modal>
  </a-card>
</template>

<script>
  import {
    GetExam,
    GetEds,
    GetSubPro,
    ActionExam
  } from '@/api/exam';
  import Moment from 'moment';
  const plainOptions = ['单选', '多选', '判断', '问答'];
  const rules = {
    idnumber: function(rule, value, callback) {
      var isIDCard1 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
      var isIDCard2 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
      if (isIDCard1.test(value)) {
        callback();
      } else if (isIDCard2.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确的身份证号码'));
      }
    },
    phone: function(rule, value, callback) {
      var valPhone = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
      if (valPhone.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确的手机号码'));
      }
    },
    isnumber: function(rule, value, callback) {
      const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
      if (!isNaN(value) && reg.test(value)) {
        callback();
      } else {
        callback('只能是数字!');
      }
    }
  };
  export default {
    components: {},
    data() {
      return {
        rules: rules,
        activeKey: '1',
        formData: {},
        plainOptions: plainOptions,
        pagesizeoptions: ['20', '50', '200', '5000'],
        disabledform: false,
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          }
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 12
          }
        },
        modal2Visible: false,
        data: [],
        edsdata: {},
        columns: [{
            title: 'ID',
            dataIndex: 'id',
            align: 'center'
          },
          {
            title: '试卷标题',
            dataIndex: 'title',
            scopedSlots: {
              customRender: 'name'
            },
            align: 'center'
          },
          {
            title: '试卷标题',
            dataIndex: 'name',
            scopedSlots: {
              customRender: 'name'
            },
            align: 'center'
          },
          {
            title: '考试时间(分)',
            dataIndex: 'time',
            align: 'center'
          },
          {
            title: '开始日期',
            dataIndex: 'stime',
            align: 'center'
          },
          {
            title: '结束日期',
            dataIndex: 'etime',
            align: 'center'
          },
          {
            title: '改卷方式',
            dataIndex: 'hascompletion',
            align: 'center',
            scopedSlots: {
              customRender: 'hascompletion'
            }
          },
          {
            title: '操作',
            dataIndex: 'display',
            key: 'x',
            scopedSlots: {
              customRender: 'action'
            },
            align: 'center'
          }
        ],
        listQuery: {
          page_size: 20,
          page_number: 1,
          order_column: 1,
          order_dir: 'asc',
          search_value: '',
          select_value: '全部'
        },
        subPro: [],
        pRos: {},
        pRo: [],
        pRoName: '',
        editExamData: {},
        total: 0
      };
    },
    beforeCreate() {
      this.form = this.$form.createForm(this);
    },
    methods: {
      handleReset(e) {},
      onSearch(value) {
        this.listQuery.search_value = value;
        this.initTable();
      },
      onShowSizeChange(current, pageSize) {
        this.listQuery.page_size = pageSize;
        this.listQuery.page_number = current;
        this.initTable();
      },
      onChange(current) {
        this.listQuery.page_number = current;
        this.initTable();
      },
      initTable() {
        var _this = this;
        GetExam(this.listQuery).then(res => {
          _this.data = res.data;
        });
      },
      handleProvinceChange(value) {
        this.pRo = this.pRos[value];
      },
      editExam(code) {
        var _this = this;
        var json = {
          examid: code
        };
        this.activeKey = '2';
        GetEds(json).then(res => {
          var data = res.data;
          _this.editExamData =data;
          console.log(data.exam.subproid.split('-'))
          _this.form.setFieldsValue({
            subjectid: Number(data.exam.subproid.split("-")[0]),
            projectid:data.exam.subproid.split('-')[1] == undefined||data.exam.subproid.split('-')[1] =='' ? '' : Number(data.exam.subproid.split('-')[1]),
            title: data.exam.title,
            stime: Moment(data.exam.stime, 'YYYY-MM-DD HH:mm:ss'),
            etime: Moment(data.exam.etime, 'YYYY-MM-DD HH:mm:ss'),
            time: data.exam.time,
            name: data.exam.name,
            describe: data.exam.describe,
            typelist: _this.hasTypeList(data.details),
            dxsize: data.details.dxsize,
            dxxsize: data.details.dxxsize,
            pdsize: data.details.pdsize,
            tksize: data.details.tksize,
            invalid: data.exam.invalid + '',
            limit: data.exam.limit,
            dxcustomscore: data.details.dxcustomscore,
            dxxcustomscore: data.details.dxxcustomscore,
            pdcustomscore: data.details.pdcustomscore,
            tkcustomscore: data.details.tkcustomscore
          });
        });
      },
      hasTypeList(details) {
        var list = [];
        if (details.dxsize > 0) {
          list.push('单选');
        }
        if (details.dxxsize > 0) {
          list.push('多选');
        }
        if (details.pdsize > 0) {
          list.push('判断');
        }
        if (details.tksize > 0) {
          list.push('问答');
        }
        return list;
      },
      setSubPro() {
        var _this = this;
        GetSubPro().then(res => {
          _this.subPro = res.data;
          var subPros = res.data;
          for (var i = 0; i < subPros.length; i++) {
            var pros = subPros[i].project;
            var prodata = [];
            for (var j = 0; j < pros.length; j++) {
              prodata.push(pros[j]);
            }
            _this.pRos[subPros[i].subject.id] = prodata;
          }
          _this.pRo = _this.pRos[_this.subPro[0].subject.id];
           let one = {
            distinction: null,
            id: '',
            name: "not select",
            subjectid: '',
          }
          _this.pRo.splice(0, 0, one);
          _this.pRoName = _this.pRo[0].name;
        });
      },
      handleSubmitSave(e) {
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err) {
            this.formData = {};
            this.showConfirm(0);
            this.formData = values;
          }
        });
      },
      handleSubmitAdd(e) {
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err) {
            this.formData = {};
            this.showConfirm(1);
            this.formData = values;
          }
        });
      },
      showConfirm(code) {
        var title = '';
        var content = '';
        var _this = this;
        if (code == 0) {
          title = '您确定要修改考试ID为' + this.editExamData.exam.id + '的数据吗？';
          content = '将修改ID为' + this.editExamData.exam.id + '的考试信息,不会开设一场新的考试!';
        } else if (code == 1) {
          title = '您确定要添加当前数据吗？';
          content = '将增开一场新的考试，当前考试数据不会发生改变!';
        }
        this.$confirm({
          title: title,
          content: content,
          onOk() {
            _this.doEditExam(code);
          },
          onCancel() {}
        });
      },
      doEditExam(code) {
        var exam = {
          describe: null,
          etime: null,
          invalid: null,
          limit: null,
          name: null,
          projectid: null,
          subproid:null,
          stime: null,
          time: null,
          title: null,
          examdetailsid: null
        };
        if (code == 0) {
          exam.id = this.editExamData.exam.id;
          exam.describe = this.formData.describe;
          exam.etime = this.formData.etime.format('YYYY-MM-DD HH:mm:ss');
          exam.invalid = this.formData.invalid;
          exam.limit = this.formData.limit;
          exam.name = this.formData.name;
          exam.subproid= this.formData.subjectid+'-'+this.formData.projectid;
          exam.stime = this.formData.stime.format('YYYY-MM-DD HH:mm:ss');
          exam.time = this.formData.time;
          exam.title = this.formData.title;
          exam.examdetailsid = this.editExamData.details.id;
          var details = {
            id: this.editExamData.details.id,
            dxsize: this.formData.dxsize,
            dxxsize: this.formData.dxxsize,
            pdsize: this.formData.pdsize,
            tksize: this.formData.tksize,
            dxcustomscore: this.formData.dxcustomscore,
            dxxcustomscore: this.formData.dxxcustomscore,
            pdcustomscore: this.formData.pdcustomscore,
            tkcustomscore: this.formData.tkcustomscore
          };
          var jquery = {
            details: details,
            exam: exam,
            action: 0
          };
          ActionExam(jquery).then(res => {
            if (res.result) {
              this.$message.success('修改成功!');
              this.initTable();
            } else {
              this.$message.error('修改失败!');
            }
          });
        } else if (code == 1) {
          exam.describe = this.formData.describe;
          exam.etime = this.formData.etime.format('YYYY-MM-DD HH:mm:ss');
          exam.invalid = this.formData.invalid;
          exam.limit = this.formData.limit;
          exam.name = this.formData.name;
          exam.subproid= this.formData.subjectid+'-'+this.formData.projectid;
          exam.stime = this.formData.stime.format('YYYY-MM-DD HH:mm:ss');
          exam.time = this.formData.time;
          exam.title = this.formData.title;
          var details = {
            dxsize: this.formData.dxsize,
            dxxsize: this.formData.dxxsize,
            pdsize: this.formData.pdsize,
            tksize: this.formData.tksize
          };
          var jquery = {
            details: details,
            exam: exam,
            action: 1
          };
          ActionExam(jquery).then(res => {
            if (res.result) {
              this.$message.success('添加成功!');
              this.initTable();
            } else {
              this.$message.error('添加失败!');
            }
          });
        }
      },
      callback(key) {
        this.activeKey = key;
      }
    },
    mounted() {
      this.initTable();
      if (this.subPro.length == 0) {
        this.setSubPro();
      }
    }
  };
</script>

<style>
  .ant-advanced-search-form {
    padding: 24px;
    background: #fbfbfb;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
  }

  .ant-advanced-search-form .ant-form-item {
    display: flex;
  }

  .ant-advanced-search-form .ant-form-item-control-wrapper {
    flex: 1;
  }

  #components-form-demo-advanced-search .ant-form {
    max-width: none;
  }

  #components-form-demo-advanced-search .search-result-list {
    margin-top: 16px;
    border: 1px dashed #e9e9e9;
    border-radius: 6px;
    background-color: #fafafa;
    min-height: 200px;
    text-align: center;
    padding-top: 80px;
  }
</style>
